package code.jzh.monitor.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import code.jzh.monitor.entity.methodinvoke.Anchor;

/**
 * 
 * @author caol
 * @since 2015-10-20
 * 实现 轨迹日志的 json格式化 以及解析
 */
public class TraceJsonUtil {
	
	public static final ThreadLocal<Long> callID = new ThreadLocal<Long>();
	
	private static String IP = "127.0.0.1";
	static {
		Enumeration<NetworkInterface> netIf;
		try {
			netIf = NetworkInterface.getNetworkInterfaces();
			while (netIf.hasMoreElements()) {
				NetworkInterface nwi = netIf.nextElement();
				Enumeration<InetAddress> address = nwi.getInetAddresses();
				while (address.hasMoreElements()) {
					InetAddress in = (InetAddress) address.nextElement();
					if (in.isSiteLocalAddress()) {
						IP = in.getHostAddress();
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}

	}

	public static String getTraceJosnStr(long time, String className, String method, int position, int isException) {
		String postionStr = "start";
		if(position == AgentConstants.METHOD_START){
			MethodMonitorUtil.addDepth();
		}else if(position == AgentConstants.METHOD_END){
			postionStr = "end";
		}
		
		int depth = MethodMonitorUtil.getDepth();
		if(isException==1)
			time = -time;
		Anchor anchor = new Anchor(depth,time,position,method);
		MethodMonitorUtil.putAnchor(anchor);
		
		StringBuffer result = new StringBuffer();
		result.append("{time:" + time + ",").append("position:"+postionStr+",").append("class:" + className + ",")
				.append("method:" + method + ",").append("ip:" + IP + ",")
				.append("depth:" + depth +"}");
		System.out.println("Premain-Class: code.jzh.monitor.service.PreAgent:" + result.toString());
		if(position == AgentConstants.METHOD_END){
			MethodMonitorUtil.subDepth();
		}
		// ProducerUtil.sendMsg(TYPE, id, result.toString());
		return result.toString();
	}
	
}
